const mainContent = document.getElementsByClassName('mainContent')[0]; //主题内容部分
const navRadio = document.getElementsByClassName('radio')[0]; //获取单选框导航层
const inputContent = document.getElementsByClassName('inputContent')[0]; // input输入框
let status1 = 'all'; // 默认为all
let timer = null;
// 封装fetch
const fetchData = (url, method, data) => {
    if (method.toUpperCase() === 'GET') {
        return fetch(url).then(response => response.json());
    }
    if (method.toUpperCase() === 'POST') {
        return fetch(url, {
            method,
            headers: {
                'content-type': 'application/json; charset=utf-8'
            },
            body: data
        }).then((response) => response.json());
    }
};
// 防抖
const debounce = (fn, wait) => {
    return (e) => {
        if (timer)
            clearTimeout(timer);
        timer = setTimeout(() => {
            fn(e);
        }, wait);
    };
};
// 节流
const throttle = (fn, wait) => {
    let canRun = true;
    return (e) => {
        if (!canRun)
            return;
        canRun = false;
        setTimeout(() => {
            fn(e);
            canRun = true;
        }, wait);
    };
};
// 创建主体部分节点
const createDOM = (list) => {
    let information;
    let moreInformation = '';
    list.forEach((item, i) => {
        information = `<div class="information">
                            <label><input type="checkbox" name="hobby" ${item.state === 1 ? "checked" : ""} onclick="modifyStatus(${item.id})"><span>${item.content}</span></label>
                            <p>
                                <button class="modify" onclick="throttle(modify(event, ${item.id}), 1000)">修改</button>
                                <button class="del" onclick="throttle(del(${item.id}), 1000)">删除</button>
                            </p>
                        </div>`;
        moreInformation = moreInformation.concat(information);
    });
    mainContent.innerHTML = moreInformation;
};
// 修改选中状态
const modifyStatus = (id) => {
    fetchData('/todo/change', 'post', JSON.stringify({ id, nowState: status1 })).then((res) => {
        createDOM(res.data);
    }).catch((err) => {
        console.log(err);
    })
};
// 删除元素
const del = (id) => {
    fetchData('/todo/del', 'post', JSON.stringify({
        id,
        nowState: status1
    })).then((res) => {
        createDOM(res.data);
    }).catch((err) => {
        console.log(err);
    });
};
// 修改接口请求
const modifyData = (id, newContent) => {
    fetchData('/todo/edit', 'post', JSON.stringify({
        id,
        newContent
    })).then(res => {
        createDOM(res.data);
    }).catch(err => {
        console.log(err);
    });
};
// 修改元素
const modify = (e, id) => {
    return () => {
        let targetLabel = e.target.parentNode.previousSibling.previousSibling;
        let input = document.createElement('input');
        for (let i = 0; i < targetLabel.childNodes.length; i++) {
            if (targetLabel.childNodes[i].nodeName === 'SPAN') {
                input.value = targetLabel.childNodes[i].innerHTML;
                targetLabel.removeChild(targetLabel.childNodes[i]);
            }
        }
        targetLabel.appendChild(input);
        input.onblur = () => {
            targetLabel.removeChild(input);
            modifyData(id, input.value);
        };
    };
};
// 输入内容加到主体内容里
const addToMain = (e) => {
    let value = e.target.value;
    // 当输入框里有值的时候在请求接口
    if (value) {
        fetchData('/todo/add', 'post', JSON.stringify({
            content: value
        })).then((res) => {
            createDOM(res.data);
        }).catch((err) => {
            console.log(err);
        });
    }
    e.target.value = '';
};
// 点击切换单选框的选中状态
const clickRadio = (e) => {
    if (e.target.nodeName === 'INPUT') {
        status1 = e.target.value;
    }
    fetchData('/todo/getList?finishState=' + status1, 'get').then((res) => {
        createDOM(res.data);
    }).catch((err) => {
        console.log(err);
    });
};
// 页面刚进入时调用获取数据接口，渲染页面
const loadPage = () => {
    fetchData('/todo/getList?finishState=all', 'get').then((res) => {
        createDOM(res.data);
    }).catch((err) => {
        console.log(err);
    });
};
loadPage();
// 输入框失去焦点时将内容加到主体里
inputContent.onblur = debounce(addToMain, 1000);
// 点击上方导航栏触发的页切事件
navRadio.onclick = debounce(clickRadio, 1000);
